package com.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.lovemanai.tools.common.CommonUtils;

public class Upload3Servlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		/*
		 * 上传三步
		 */
		//工厂
		DiskFileItemFactory factory = new DiskFileItemFactory(100*1024, new File("F:/temp"));
		//解析器
		ServletFileUpload sfu = new ServletFileUpload(factory);
//		sfu.setFileSizeMax(100 * 1024);//设置单个文件大小限制为100K
//		sfu.setSizeMax(1024 * 1024);//设置整个表单大小限制为1M
		//注意,设置大小限制必须在解析之前
		try {
			//获得FileItem集合
			List<FileItem> fileItemList = sfu.parseRequest(request);
			//单个文件大小超出限制抛出:FileUploadBase.FileSizeLimitExceededException
			//表单大小超出限制抛出:FileUploadBase.SizeLimitExceededException
			FileItem fi = fileItemList.get(1);
			
			////////////////////////////////////
			
			/*
			 * 1.得到文件保存的根路径
			 */
			String root = this.getServletContext().getRealPath("/WEB-INF/uploadfiles");
			
			/*
			 * 哈希打散
			 * 2.生成二级目录
			 * 1).得到文件名
			 * 2).得到文件哈希值
			 * 3).转换成16进制值字符串
			 * 4).获取前两个字符作为文件目录
			 */
			String filename = fi.getName();
			
			int index = filename.lastIndexOf("\\");
			
			//处理部分浏览器使用绝对路径的问题
			if(index != -1) {
				filename = filename.substring(index + 1);
			}
			String savaname = CommonUtils.uuid() + "_" +filename;//生成随机随机字符串作为文件名前缀
 			
			int fileHashCode = filename.hashCode();//获取文件哈希值
			
			String hex = Integer.toHexString(fileHashCode);//转换成16进制字符串
			
			/*
			 * 获取hex的前两个字符与root连起来生成完整路径
			 */
			File filedir = new File(root, hex.charAt(0) + "/" + hex.charAt(1));
			
			//创建目录链
			filedir.mkdirs();
			
			//创建目录文件
			File destFile = new File(filedir, savaname);
			
			fi.write(destFile);
			
			////////////////////////////////////
		} catch (FileUploadException e) {
			if(e instanceof FileUploadBase.FileSizeLimitExceededException) {
				request.setAttribute("msg", "您上传的附件超出了最大100KB限制");
				request.getRequestDispatcher("/form3.jsp").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}




